package com.aaa.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * fileName:ClusterRedisLock
 * description: 通用的分布式锁工具类
 * author: znb
 * createTime:2020/12/21 0021 14:17
 * version:1.0.0
 */
@Component //交给spring管理
@SuppressWarnings("all")
public class ClusterRedisLock {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 加锁方法
     * @param key
     * @param second
     * @return
     */
    public boolean lock(String key,int second){
        //setnx(key,val) 不存在时设置值   expire(key,60000)   设置过期时间
        return   redisTemplate.opsForValue().setIfAbsent(key,"clusterLock",second, TimeUnit.SECONDS);
    }

    /**
     * 解锁  业务执行完成，删除锁
     * @param key
     * @return
     */
    public  boolean unLock(String key){
        // delete(key)  业务执行完成删除
        return redisTemplate.delete(key);
    }

}
